#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmessagebox.h"
#include "qdebug.h"

char MainWindow:: Com_Flash(void) //刷新串口 char放在前面
{
    char com_num=0;//统计串口数目
    foreach(const  QSerialPortInfo  &info,QSerialPortInfo::availablePorts())//可以不使用
    {
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            com_num++;
            ui->comboBox->addItem(serial.portName());//添加端口号 如果只有一个的话 就是当前显示的
            serial.close();
        }
    }//自动搜寻串口号并保存

    return com_num;
}

MainWindow::MainWindow(QWidget *parent) :  QMainWindow(parent), ui(new Ui::MainWindow),serial(new QSerialPort(this))//,timer(new QTimer(this))
{
    ui->setupUi(this);
    setWindowTitle("GKoSon串口调试助手V1.0");//serial  在Mywidget头文件中
    ui->pushButton_1->setEnabled(true);//连接
    ui->pushButton_2->setEnabled(false);//发送
    ui->pushButton_3->setEnabled(false);//断开

    comcount=Com_Flash();



        btnGroupsend = new QButtonGroup(this);
        btnGroupsend->addButton(ui->radioButton, 0);
        btnGroupsend->addButton(ui->radioButton_2, 1);
        ui->radioButton->setChecked(true);
        btnGroupreceive = new QButtonGroup(this);
        btnGroupreceive->addButton(ui->radioButton_3, 0);
        btnGroupreceive->addButton(ui->radioButton_4, 1);
        ui->radioButton_3->setChecked(true);

        connect(ui->radioButton,  SIGNAL(clicked()), this, SLOT(onRadioClickSend()));
        connect(ui->radioButton_2, SIGNAL(clicked()), this, SLOT(onRadioClickSend()));


        connect(ui->radioButton_3, SIGNAL(clicked()), this, SLOT(onRadioClickRceived()));
        connect(ui->radioButton_4, SIGNAL(clicked()), this, SLOT(onRadioClickRceived()));

    timer = new QTimer(this);
 //   作者：PeOS
 //  来源：CSDN
 //   原文：https://blog.csdn.net/cxp2205455256/article/details/44956051
 //   版权声明：本文为博主原创文章，转载请附上博文链接！ 用分组的思路 现在可以2个选中了
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::onRadioClickRceived()
{
    switch(btnGroupreceive->checkedId())
    {
       case 0:
           qDebug() << QString::fromLocal8Bit("1");
           break;
       case 1:
           qDebug()  << QString::fromLocal8Bit("2");
    }


}

void MainWindow::onRadioClickSend()
{
    switch(btnGroupsend->checkedId())
    {
       case 0:
           qDebug() << QString::fromLocal8Bit("3");
           break;
       case 1:
           qDebug()  << QString::fromLocal8Bit("4");
    }


}
//打开
void MainWindow::on_pushButton_1_clicked()
{

    //判断是否有com

    if(ui->comboBox->currentText()=="")
    {
       QMessageBox::about(NULL, "Warn", "<font color='red'>No Com</font>");
       comcount=Com_Flash();
       return;
    }


    serial.setPortName(ui->comboBox->currentText());
    serial.open(QIODevice::ReadWrite);
    qint32 bar=ui->comboBox_2->currentText().toInt();
    //cout<<bar;
    qDebug() << "bar is :"<<bar;
    serial.setBaudRate(bar);
    serial.setParity(QSerialPort::NoParity);//无校验
    serial.setDataBits(QSerialPort::Data8);//设置数据位
    serial.setStopBits(QSerialPort::OneStop);
   //利用串口中断接收 serial.setDataTerminalReady(true);//https://blog.csdn.net/ryanpinwei/article/details/52203668
    ui->pushButton_1->setEnabled(false);//连接
    ui->pushButton_2->setEnabled(true);//发送
    ui->pushButton_3->setEnabled(true);//断开

    //timer = new QTimer(this);
    connect( timer, SIGNAL( timeout() ), this, SLOT( readyReadSlot() ) );
    timer->start(1000);//每秒读一次
    connect( &serial, SIGNAL( readyRead() ), this, SLOT( comreadyReadSlot() ) );

}


char MainWindow:: GetHexBitsValue(char ch)
       {
           char sz = 0;
           if (ch <= '9' && ch >= '0')
               sz = (ch - 0x30);
           if (ch <= 'F' && ch >= 'A')
               sz = (ch - 0x37);
           if (ch <= 'f' && ch >= 'a')
               sz = (ch - 0x57);

           return sz;
       }

QByteArray MainWindow:: ToDigitsBytes(char* theHex)
       {
           QByteArray  bytes ;
           bytes.resize(strlen(theHex) / 2 + (((strlen(theHex) % 2) > 0) ? 1 : 0));

           for (int i = 0; i < bytes.length(); i++)
           {
               char lowbits = theHex[i * 2];
               char highbits;

               if ((i * 2 + 1) <strlen(theHex))
                   highbits = theHex[i * 2 + 1];
               else
                   highbits = '0';

               int a = (int)GetHexBitsValue(lowbits);
               int b = (int)GetHexBitsValue(highbits);
               bytes[i] = (unsigned char)((a << 4) + b);
           }

           return bytes;
       }

//发送
void MainWindow::on_pushButton_3_clicked()
{
    if(ui->radioButton->isChecked() ==true)//没有用分组的思路 用的是埃士时期的判断 发string
        serial.write(ui->textEdit_2->toPlainText().toUtf8().data());
    else if(ui->radioButton_2->isChecked()==true)//发hex
        serial.write(ToDigitsBytes(ui->textEdit_2->toPlainText().toUtf8().data()));
    qDebug() << "send:"<<ui->textEdit_2->toPlainText().toUtf8().data();
}

//断开
void MainWindow::on_pushButton_2_clicked()
{
    serial.close();//关闭
    ui->pushButton_1->setEnabled(true);//连接
    ui->pushButton_2->setEnabled(false);//发送
    ui->pushButton_3->setEnabled(false);//断开
    timer->stop();
}

//接收
void MainWindow::readyReadSlot()
{
    #if 0
      requestData = serial.readAll();//用requestData存储从串口那读取的数据<可以：HELLO123 不可以龚金华 汉字无法表达>
       if(requestData!=NULL)//如果读取到有数据，就显示出来。
       {
           ui->textEdit->append(requestData);
       }
       requestData.clear();    //清除缓冲区
    #endif
         qDebug() << "hello";
}

void MainWindow::comreadyReadSlot()
{
    requestData = serial.readAll();//用requestData存储从串口那读取的数据<可以：HELLO123 不可以龚金华 汉字无法表达>
     if(requestData!=NULL)//如果读取到有数据，就显示出来。
     {
         ui->textEdit->append(requestData);
     }
     requestData.clear();    //清除缓冲区

}

void MainWindow::on_pushButton_4_clicked()
{
     ui->textEdit->clear();
}
